import 'dart:async';

import 'package:battery_plus/battery_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wakelock/wakelock.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([]);
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    return const MaterialApp(
      title: '氢时',
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Wakelock.enabled.then((value) {
      if (!value) Wakelock.enable();
      debugPrint("wake lock has enable.");
    });

    return Scaffold(
      body: SizedBox.expand(
        child: Stack(
          children: const [
            Align(
              alignment: Alignment(-0.5, 0),
              child: TimeText(),
            ),
            Positioned(
              top: 16.0,
              right: 16.0,
              // bottom: 16.0,
              child: BatteryLevel(),
            ),
          ],
        ),
      ),
    );
  }
}

class TimeText extends StatefulWidget {
  const TimeText({Key? key}) : super(key: key);

  @override
  _TimeTextState createState() => _TimeTextState();
}

class _TimeTextState extends State<TimeText> {
  late DateTime dateTime;
  String hour = "00";
  String minute = "00";
  String second = "00";

  final listen = Stream.periodic(const Duration(seconds: 1));

  @override
  void initState() {
    super.initState();

    listen.listen((event) {
      setState(() {
        dateTime = DateTime.now();
        hour = timeToString(dateTime.hour);
        minute = timeToString(dateTime.minute);
        second = timeToString(dateTime.second);
      });
    });
  }

  String timeToString(int t) => t < 10 ? "0$t" : t.toString();

  @override
  Widget build(BuildContext context) {
    return Text(
      "$hour:$minute:$second",
      style: const TextStyle(fontSize: 56),
    );
  }
}

class BatteryLevel extends StatefulWidget {
  const BatteryLevel({Key? key}) : super(key: key);

  @override
  _BatteryLevelState createState() => _BatteryLevelState();
}

class _BatteryLevelState extends State<BatteryLevel> {
  int level = -1;
  final stream = Stream.periodic(const Duration(minutes: 1));
  final battery = Battery();

  @override
  void initState() {
    super.initState();

    battery.batteryLevel.then(
      (value) => setState(() {
        level = value;
      }),
    );
    stream.listen(
      (event) async {
        var batteryLevel = await battery.batteryLevel;
        setState(() {
          level = batteryLevel;
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<BatteryState>(
      stream: battery.onBatteryStateChanged,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.active) {
          return const CircularProgressIndicator();
        }
        IconData iconData;
        switch (snapshot.data) {
          case BatteryState.full:
            iconData = Icons.battery_full_rounded;
            break;
          case BatteryState.charging:
            iconData = Icons.battery_charging_full_rounded;
            break;
          case BatteryState.discharging:
            iconData = Icons.battery_std_rounded;
            break;
          case null:
          case BatteryState.unknown:
            iconData = Icons.battery_unknown_rounded;
            break;
        }
        if (level < 20 && iconData != Icons.battery_charging_full_rounded) {
          iconData = Icons.battery_alert_rounded;
        }
        return Row(
          children: [
            Text(
              "$level%",
              style: const TextStyle(fontSize: 32.0),
            ),
            Icon(
              iconData,
              size: 32.0,
            ),
          ],
        );
      },
    );
  }
}
